import { TypeOrmModuleOptions } from "@nestjs/typeorm";
import { Logs } from "./src/logs/logs.entity";
import { Roles } from "./src/roles/roles.entity";
import { Profile } from "./src/user/profile.entity";
import { User } from "./src/user/user.entity";
import { Menus } from "./src/menus/menu.entity";
import { DataSource, DataSourceOptions } from "typeorm";
import * as fs from "node:fs";
import * as dotenv from "dotenv";
import { ConfigEnum } from "./src/enum/config.enum";
import { Type } from "@nestjs/common";

type Config = TypeOrmModuleOptions & { redis_pwd: string };

/**
 * 读取环境变量配置文件
 * @param env 环境变量文件
 */
const getEnv = (env: string): Record<string, unknown> => {
  if (fs.existsSync(env)) {
    return dotenv.parse(fs.readFileSync(env));
  }
  return {};
};

const buildConnectionOptions = (): Config => {
  const defaultConfig = getEnv(".env");
  const envConfig = getEnv(`.env.${process.env.NODE_ENV || "development"}`);
  // configServer
  const config = { ...defaultConfig, ...envConfig };

  // 动态导入有可能因为路径解析错误导致报错
  // const entitiesDir =
  //   process.env.NODE_ENV === "test"
  //     ? [process.cwd() + "/src/**/*.entity.ts"]
  //     : [process.cwd() + "/dist/src/**/*.entity.js", process.cwd() + "/src/**/*.entity.ts"];

  return {
    // connectorPackage: "mysql2",
    type: config[ConfigEnum.DB_TYPE],
    host: config[ConfigEnum.DB_HOST],
    port: config[ConfigEnum.DB_PORT],
    username: config[ConfigEnum.DB_USERNAME],
    password: config[ConfigEnum.DB_PASSWORD],
    database: config[ConfigEnum.DB_DATABASE],
    redis_pwd: config[ConfigEnum.REDIS_PASSWORD],
    entities: [User, Profile, Logs, Roles, Menus],
    // entities: entitiesDir,
    // 同步本地的 schema 与数据库 -> 初始化时候使用
    synchronize: config[ConfigEnum.DB_SYNC],
    // logging: ["error"],
    // 添加连接成功的回调，用于输出日志
    logging: config[ConfigEnum.DB_LOGGING],
  } as Config;
};

export const connectionParams = buildConnectionOptions();

export default new DataSource({
  ...connectionParams,
  migrations: ["src/migrations/*.ts"],
  subscribers: [],
} as DataSourceOptions);
